<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

require_once APPPATH . 'controllers/admin.php';

/**
 * Контроллер импорта контента из XML файла
 *
 * @package CoreFramework
 * @version 1.0
 * @author Gennadiy Kozlenko
 */
class Admin_Import_Contents extends Admin {
   
   /**
    * Конструктор класса
    *
    * @access public
    * @return Admin_Import_Contents
    */
   function Admin_Import_Contents() {
      parent::Admin();
      $this->set_menu(4, 5);
   } // end Admin_Imoport_Contents
   
   /**
    * Метод по умолчанию
    *
    * @access public
    */
   function index() {
      $id_menu = 0;
      $override_exists = false;
      $this->load->model('m_table');
      
      if (false !== $this->input->post('import')) {
         $id_menu = (int) $this->input->post('menu');
         $override_exists = (bool) $this->input->post('override_exists');
         $result = true;
         if (0 == $id_menu) {
            $this->errors->set('menu', $this->lang->line('choose_menu'));
            $result = false;
         }
         // Загружаем файл
         $xml = '';
         $config = array(
            'upload_path'   => $this->config->item('upload_path'),
            'allowed_types' => 'xml',
            'encrypt_name'  => true
         );
         $this->load->library('upload', $config);
         if ($this->upload->do_upload('file')) {
            $file_data = $this->upload->data();
            // Получаем содержимое файла
            $xml = file_get_contents($file_data['full_path']);
            // Удаляем файл из временной папки
            @unlink($file_data['full_path']);
         } else {
            $this->errors->set('file', $this->upload->display_errors('', ''));
            $result = false;
         }
         
         if ($result) {
            $count = $this->_import($id_menu, $xml, $override_exists);
            if (false === $count) {
               $this->set_message($this->lang->line('import_contents_error'), 'error');
            } elseif (0 == $count) {
               $this->set_message($this->lang->line('no_import_contents'), 'info', true);
               $this->redirect($this->get_controller());
            } else {
               $this->set_message(str_replace('{%count%}', $count, $this->lang->line('import_contents_succ')), 'info', true);
               $this->redirect($this->get_controller());
            }
         }
      }
      
      // Получаем список меню
      $items = array(0 => $this->lang->line('choose'));
      $this->m_table->set_table('menus');
      $this->m_table->add_restriction('status', 'active');
      $this->m_table->add_sort('position');
      $this->m_table->load_results();
      foreach ($this->m_table->get_results() as $result) {
         $items[$result['id_menu']] = $result['title'];
      }
      
      // Заполняем массив data
      $this->load->helper('element');
      $data = array(
         'id_menu'         => $id_menu,
         'menus'           => create_select('menu', $items, $id_menu, 'class="i"'),
         'override_exists' => create_checkbox('override_exists', $override_exists, 'id="override_exists"')
      );
      $this->set_content($this->parser->parse('admin/import_contents.html', $data, true));
      $this->display();
   } // end index
   
   /**
    * Импортирование xml файла в меню
    *
    * @param integer $id_menu
    * @param string $xml
    * @param boolean $override
    * @return mixed
    */
   function _import($id_menu, $xml, $override = false) {
      // Строим массив данных
      $contents = array();
      $matches = array();
      if (preg_match_all('~<item>(.*?)</item>~msi', $xml, $matches)) {
         for ($i = 0; $i < count($matches[1]); $i++) {
            $item = $matches[1][$i];
            $match = array();
            // id_content
            $id_content = 0;
            if (preg_match('~<wp:post_id>(\d+)</wp:post_id>~msi', $item, $match)) {
               $id_content = (int) $match[1];
            }
            // id_parent
            $id_parent = null;
            if (preg_match('~<wp:post_parent>(\d+)</wp:post_parent>~msi', $item, $match)) {
               $id_parent = (int) $match[1];
               if (0 == $id_parent) {
                  $id_parent = null;
               }
            }
            // position
            $position = 0;
            if (preg_match('~<wp:menu_order>(\d+)</wp:menu_order>~msi', $item, $match)) {
               $position = (int) $match[1];
            }
            // datetime
            $datetime = time();
            if (preg_match('~<wp:post_date>([^<]+)</wp:post_date>~msi', $item)) {
               $datetime = mysql_to_unix($match[1]);
            }
            // status
            $status = 'paused';
            if (preg_match('~<wp:status>publish</wp:status>~msi', $item, $match)) {
               $status = 'active';
            }
            // title
            $title = '';
            if (preg_match('~<title>(.*?)</title>~msi', $item, $match)) {
               $title = trim(str_replace(array('<![CDATA[', ']]>'), '', $match[1]));
            }
            // content
            $content = '';
            if (preg_match('~<content:encoded>(.*?)</content:encoded>~msi', $item, $match)) {
               $content = nl2br(trim(str_replace(array('<![CDATA[', ']]>'), '', $match[1])));
            }
            if (0 < $id_content && !empty($title)) {
               $value = array(
                  'id_content' => $id_content,
                  'id_parent'  => $id_parent,
                  'position'   => $position,
                  'datetime'   => $datetime,
                  'status'     => $status,
                  'title'      => $title,
                  'content'    => $content
               );
               array_push($contents, $value);
            }
         }
      }
      // Сортируем по позиции
      usort($contents, create_function('$a,$b', 'return $a["position"] > $b["position"] ? 1 : -1;'));
      // Строим дерево
      $this->load->helper('tree');
      $tree = array_tree($contents, 'id_content', 'id_parent');
      $contents = collapse_tree($tree, 'level');
      
      // Очищаем меню, если это необходимо
      if ($override) {
         $this->load->model('m_menu');
         $this->m_menu->set_id($id_menu);
         $this->m_menu->delete_contents();
      }
      // Прохидимся по каждому контенту и заносим в базу
      $map = array();
      $this->load->helper('text');
      $this->load->model('m_content');
      foreach ($contents as $content) {
         $id_parent = $content['id_parent'];
         if (null !== $id_parent) {
            $id_parent = isset($map[$id_parent]) ? $map[$id_parent] : null;
         }
         $this->m_content->set_id(0);
         $this->m_content->set('id_parent', $id_parent);
         $this->m_content->set('id_menu', $id_menu);
         $this->m_content->set('position', $content['position']);
         $this->m_content->set('datetime', $content['datetime']);
         $this->m_content->set('status', $content['status']);
         $this->m_content->set('link', '');
         $this->m_content->set('title', $content['title']);
         $this->m_content->set('content', $content['content']);
         // Генерируем uri segment
         // Транслитерируем
         $uri_segment = transliteration($content['title']);
         // Строим урл
         $uri_segment = url_title($uri_segment, 'dash', true);
         // Лимитируем
         $uri_segment = substr($uri_segment, 0, 200);
         // Подстраиваем uri segment так, чтобы он был уникальным в пределах нужного уровня
         $i = 0;
         $sep = '-';
         if (empty($uri_segment)) {
            $sep = '';
         }
         $name = $uri_segment;
         while (empty($name) || !$this->check_content_name($name, $id_parent, $id_menu)) {
            $name = $uri_segment . $sep . (string) ++$i;
         }
         $this->m_content->set('name', $name);
         if ($this->m_content->update()) {
            $id_content = $this->m_content->get_id('id_content');
            $map[$content['id_content']] = $id_content;
         }
      }
      
      return count($contents);
   } // end _import
   
   /**
    * Функция валидирования uri сегмента на уникальность
    *
    * @access public
    * @param string $name
    * @param mixed $id_parent
    * @param integer $id_menu
    * @return boolean
    */
   function check_content_name($name, $id_parent, $id_menu) {
      $this->m_table->set_table('contents');
      $this->m_table->add_restriction('name', $name);
      $this->m_table->add_restriction('id_parent', $id_parent);
      $this->m_table->add_restriction('id_menu', $id_menu);
      $this->m_table->set_limit(1);
      $this->m_table->load_results();
      if (0 == $this->m_table->get_count()) {
         return true;
      }
      return false;
   } // end check_content_name
   
}
